package com.syjy.tunnelworker.workassist.iec104tcp;




import com.syjy.container.ProtocolDataContainer;
import com.syjy.tunnelinfo.DataPoint;
import wei.yigulu.iec104.annotation.AsduType;
import wei.yigulu.iec104.apdumodel.Apdu;
import wei.yigulu.iec104.asdudataframe.TotalSummonType;
import wei.yigulu.iec104.nettyconfig.Iec104HSMasterBuilder;
import wei.yigulu.iec104.nettyconfig.Iec104SlaverBuilder;
import wei.yigulu.iec104.util.SendDataFrameHelper;
import wei.yigulu.netty.BaseProtocolBuilder;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理总召唤帧
 *
 * @author 修唯xiuwei
 * @version 3.0
 */
@AsduType(typeId = 100)
public class HandleTotalSummon extends TotalSummonType {


	@Override
	public byte[][] handleAndAnswer(Apdu apdu) throws Exception {
		apdu.getLog().trace("----------响应总召唤---------");
		BaseProtocolBuilder builder = apdu.getIec104Builder();

		Map<String, Object> confMap = builder.getConfigInfoMap();
		//当该帧是由 SlaverBuilder 或其子类接收到的  且为总召唤原因为激活
		if (builder instanceof Iec104SlaverBuilder) {
			if (apdu.getAsdu().getCot().getNot() == 6) {
				//响应总召唤 激活确认帧
				SendDataFrameHelper.sendTotalSummonFrame(apdu.getChannel(), apdu.getAsdu().getCommonAddress(), 7, builder.getLog());
				//响应遥信
				if (confMap.get("yx") != null) {
					Map<Integer, DataPoint> yxDataPoints = (Map<Integer, DataPoint>) confMap.get("yx");
					Map<Integer,Boolean> yx=new HashMap<>();
					yxDataPoints.forEach((k,v)->{
						yx.put(k, ProtocolDataContainer.getInstance().getBoolean(v.getId()));
					});
					SendDataFrameHelper.sendYxDataFrame(apdu.getChannel(), yx, apdu.getAsdu().getCommonAddress(), 20, builder.getLog());
				}
				//响应遥测
				if (confMap.get("yc") != null) {
					Map<Integer, DataPoint> ycDataPoints = (Map<Integer, DataPoint>) confMap.get("yc");
					Map<Integer,Number> yc=new HashMap<>();
					ycDataPoints.forEach((k,v)->{
						yc.put(k, ProtocolDataContainer.getInstance().getNumber(v.getId()).multiply(BigDecimal.valueOf(v.getMag())));
					});
					SendDataFrameHelper.sendYcDataFrame(apdu.getChannel(), yc, apdu.getAsdu().getCommonAddress(), 20, builder.getLog());
				}
				//响应总召唤 激活停止帧
				SendDataFrameHelper.sendTotalSummonFrame(apdu.getChannel(), apdu.getAsdu().getCommonAddress(), 8, builder.getLog());
			} else if (apdu.getAsdu().getCot().getNot() == 9) {
				SendDataFrameHelper.sendTotalSummonFrame(apdu.getChannel(), apdu.getAsdu().getCommonAddress(), 10, builder.getLog());
			}
		}
		// 如果是master 接收到停止激活帧
		else if (builder instanceof Iec104HSMasterBuilder) {
			if (apdu.getAsdu().getCot().getNot() == 8) {
				//响应总召唤 确认激活停止帧
				SendDataFrameHelper.sendTotalSummonFrame(apdu.getChannel(), apdu.getAsdu().getCommonAddress(), 9, builder.getLog());
			}
		}
		return null;
	}


}
